<?php
namespace Wish\Controller;

use Think\Controller;
use Think\Model;

class IndexController extends Controller
{
    public function index()
    {
        $model = M('Wish');
        $wishs = $model->select();
        $this->assign('wishs', $wishs)->display();
    }

    public function  add()
    {
        if (!IS_POST) $this->error("非法操作!", "index", 3);
        $username = I('post.username');
        $content = I('post.content');
        if ($username == "") $this->error("昵称不能为空!", "index", 3);
        if ($content == "") $this->error("愿望不能为空!", "index", 3);
        $data["Username"] = $username;
        $data["Content"] = $content;
        $data["Time"] = time();
        $wish = M('Wish');
        $result = $wish->data($data)->add();
        if ($result) {
            $this->success("许愿成功!", "index", 3);
        } else {
            $this->error("许愿失败!", "index", 3);
        }
    }

    public function  ajaxAdd()
    {
        //验证POST数据
        if (!IS_AJAX) $this->error("非法操作", "index", 5);
        $username = I('post.username');
        $content = I('post.content');
        if ($username == "") $this->error("昵称不能为空!", "index", 3);
        if ($content == "") $this->error("愿望不能为空!", "index", 3);
        //添加数据
        $data["Username"] = $username;
        $data["Content"] = $content;
        $data["Time"] = time();
        $wish = M('Wish');
        $result = $wish->data($data)->add();
        //验证添加结果并响应
        if ($result) {
            $data["Status"] = "1";
            $data["ID"] = $result;
            $data["Message"] = "许愿成功!";
            $this->ajaxReturn($data);
        } else {
            $data = null;
            $data["Status"] = "-1";
            $data["Message"] = "许愿失败!";
            $this->ajaxReturn($data);
        }
    }


    public function  delete()
    {
        $id = I('get.id');
        if (!is_numeric($id)) $this->error("非法操作", 'index', 5);
        $model = M('Wish');
        $model->delete($id);
    }
}